package com.hltc.mtmap.orm;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.hltc.mtmap.MTComment;
import com.hltc.mtmap.MTGrain;
import com.hltc.mtmap.MTUser;

import com.hltc.mtmap.MTComment;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/**
 * DAO for table MTCOMMENT.
 */
public class MTCommentDao extends AbstractDao<MTComment, Long> {

    public static final String TABLENAME = "MTCOMMENT";
    private DaoSession daoSession;
    ;
    private Query<MTComment> mTUser_Comments2UserQuery;
    private Query<MTComment> mTGrain_Comments2GrainQuery;
    private Query<MTComment> mTComment_ChildrenQuery;
    private String selectDeep;

    public MTCommentDao(DaoConfig config) {
        super(config);
    }

    public MTCommentDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /**
     * Creates the underlying database table.
     */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists ? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'MTCOMMENT' (" + //
                "'_id' INTEGER PRIMARY KEY NOT NULL ," + // 0: id
                "'CONTENT' TEXT NOT NULL ," + // 1: content
                "'DATE' INTEGER NOT NULL ," + // 2: date
                "'TO_COMMENT_ID' INTEGER," + // 3: toCommentId
                "'USER_ID' INTEGER," + // 4: userId
                "'GRAIN_ID' INTEGER NOT NULL );"); // 5: grainId
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'MTCOMMENT'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, MTComment entity) {
        stmt.clearBindings();
        stmt.bindLong(1, entity.getId());
        stmt.bindString(2, entity.getContent());
        stmt.bindLong(3, entity.getDate().getTime());
 
        Long toCommentId = entity.getToCommentId();
        if (toCommentId != null) {
            stmt.bindLong(4, toCommentId);
        }
 
        Long userId = entity.getUserId();
        if (userId != null) {
            stmt.bindLong(5, userId);
        }
        stmt.bindLong(6, entity.getGrainId());
    }

    @Override
    protected void attachEntity(MTComment entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public MTComment readEntity(Cursor cursor, int offset) {
        MTComment entity = new MTComment( //
                cursor.getLong(offset + 0), // id
                cursor.getString(offset + 1), // content
                new java.util.Date(cursor.getLong(offset + 2)), // date
                cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3), // toCommentId
                cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // userId
                cursor.getLong(offset + 5) // grainId
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, MTComment entity, int offset) {
        entity.setId(cursor.getLong(offset + 0));
        entity.setContent(cursor.getString(offset + 1));
        entity.setDate(new java.util.Date(cursor.getLong(offset + 2)));
        entity.setToCommentId(cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3));
        entity.setUserId(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
        entity.setGrainId(cursor.getLong(offset + 5));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(MTComment entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(MTComment entity) {
        if (entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "comments2User" to-many relationship of MTUser. */
    public List<MTComment> _queryMTUser_Comments2User(Long userId) {
        synchronized (this) {
            if (mTUser_Comments2UserQuery == null) {
                QueryBuilder<MTComment> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.UserId.eq(null));
                mTUser_Comments2UserQuery = queryBuilder.build();
            }
        }
        Query<MTComment> query = mTUser_Comments2UserQuery.forCurrentThread();
        query.setParameter(0, userId);
        return query.list();
    }

    /** Internal query to resolve the "comments2Grain" to-many relationship of MTGrain. */
    public List<MTComment> _queryMTGrain_Comments2Grain(long grainId) {
        synchronized (this) {
            if (mTGrain_Comments2GrainQuery == null) {
                QueryBuilder<MTComment> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.GrainId.eq(null));
                mTGrain_Comments2GrainQuery = queryBuilder.build();
            }
        }
        Query<MTComment> query = mTGrain_Comments2GrainQuery.forCurrentThread();
        query.setParameter(0, grainId);
        return query.list();
    }

    /** Internal query to resolve the "children" to-many relationship of MTComment. */
    public List<MTComment> _queryMTComment_Children(Long toCommentId) {
        synchronized (this) {
            if (mTComment_ChildrenQuery == null) {
                QueryBuilder<MTComment> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.ToCommentId.eq(null));
                mTComment_ChildrenQuery = queryBuilder.build();
            }
        }
        Query<MTComment> query = mTComment_ChildrenQuery.forCurrentThread();
        query.setParameter(0, toCommentId);
        return query.list();
    }

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getMTUserDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getMTGrainDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T2", daoSession.getMTCommentDao().getAllColumns());
            builder.append(" FROM MTCOMMENT T");
            builder.append(" LEFT JOIN MTUSER T0 ON T.'USER_ID'=T0.'USER_ID'");
            builder.append(" LEFT JOIN MTGRAIN T1 ON T.'GRAIN_ID'=T1.'GRAIN_ID'");
            builder.append(" LEFT JOIN MTCOMMENT T2 ON T.'TO_COMMENT_ID'=T2.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }

    protected MTComment loadCurrentDeep(Cursor cursor, boolean lock) {
        MTComment entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        MTUser mTUser = loadCurrentOther(daoSession.getMTUserDao(), cursor, offset);
        entity.setMTUser(mTUser);
        offset += daoSession.getMTUserDao().getAllColumns().length;

        MTGrain mTGrain = loadCurrentOther(daoSession.getMTGrainDao(), cursor, offset);
        if (mTGrain != null) {
            entity.setMTGrain(mTGrain);
        }
        offset += daoSession.getMTGrainDao().getAllColumns().length;

        MTComment parent = loadCurrentOther(daoSession.getMTCommentDao(), cursor, offset);
        entity.setParent(parent);

        return entity;
    }
    
    public MTComment loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();

        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);

        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }

    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<MTComment> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<MTComment> list = new ArrayList<MTComment>(count);

        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<MTComment> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    
    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<MTComment> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
    
/**
     * Properties of entity MTComment.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, long.class, "id", true, "_id");
        public final static Property Content = new Property(1, String.class, "content", false, "CONTENT");
        public final static Property Date = new Property(2, java.util.Date.class, "date", false, "DATE");
        public final static Property ToCommentId = new Property(3, Long.class, "toCommentId", false, "TO_COMMENT_ID");
        public final static Property UserId = new Property(4, Long.class, "userId", false, "USER_ID");
        public final static Property GrainId = new Property(5, long.class, "grainId", false, "GRAIN_ID");
    }
 
}
